

from threading import Thread
from AGDefines import *
from Enum import *
from ZhangHao import *
from SuanGua import *
from ShiMen import *
from BaoTu import *
from PinTu import *
from TongJi import *
from HuanJing import *

from Log2File import *

logger = logging.getLogger(__name__)


class Role(Thread):
    #emulator-5554
    #127.0.0.1:7555

    def __init__(self, roleName, dailyList, port):
        Thread.__init__(self)

        self.name = roleName
        self.dailyList = dailyList
        self.enum = Enum(port)
        self.dailyObjList = {}
        self.started = False

        Log2File.init(port)

        for dai in self.dailyList:
            logger.info("daily " + dai)
            self.dailyObjList[dai] = self.createRiChang(dai)

        logger.info("dailyObjList len " + str(len(self.dailyObjList)))

        self.currDaily = self.dailyList[0]

        logger.info("current daily " + self.currDaily)

    def startUp(self):

        self.started = True

        logger.info("id {} start!!!".format(self.name))
        Log2File.info(self.enum.port, "id {} start!!!".format(self.name))

        for key in self.dailyObjList:
            if self.started == False:
                return
            self.currDaily = key
            self.dailyObjList[self.currDaily].KaiShi()


    def run(self):
        print ("开始线程：" + self.name)
        zhanghaoList = [
            #['md1xwl', 'xwl123'],
            #['md2xwl', 'xwl123'],
            #['md3xwl', 'xwl123'],
            #['md4xwl', 'xwl123'],
            ['md5xwl', 'xwl123'],
        ]
        self.started = True

        self.startUp()

        zhangHaoswitch = ZhangHao(self.enum)
        for zhanghao in zhanghaoList:
            if self.started == False:
                break
            zhangHaoswitch.switchHao(zhanghao[0], zhanghao[1])
            self.startUp()
        print ("退出线程：" + self.name)


    def stop(self):
        logger.info("stop all " + self.name)
        self.started = False
        self.dailyObjList[self.currDaily].stop()

    def createRiChang(self, name):
        if name == "ShiMen":
            return ShiMen(self.enum)
        elif name == "PinTu":
            return PinTu(self.enum)
        elif name == "BaoTu":
            return BaoTu(self.enum)
        elif name == 'SuanGua':
            return SuanGua(self.enum)
        elif name == 'TongJi':
            return TongJi(self.enum)
        elif name == 'HuanJing':
            return HuanJing(self.enum)